define(function(require, exports){
	var $ = require("jquery");
	var pubjs = require('pubjs');
	var view  = require('@base/view');
	var util	= require('util');


	var Main = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'class': 'P-dspUser',
				'urlRemove': 'user/remove',
				'urlSwitchUser': 'user/switchUser',
				'isSubGrid': false,
				'hasHead': true, // 是否有头部标题
				'grid_config': null, // 列表配置
				'gridName': 'customer',
				'view_model':{

				}
			});
			this.Super('init', arguments);

			//	财务审核权限
			this.$financeAuditAddRight = pubjs.checkRight('financeAudit.add');
			//	设置用户每日预算权限
			this.$userBudgetRight = pubjs.checkRight('user.dailyBudget');
		},
		afterBuild:function(){
			var self = this;
			var c = self.getConfig();
			var el = self.getDOM();

			self.append($([
				'<div class="M-formHead">',
					// '<span class="M-formHeadTitle">'+LANG('客户列表')+'</span>',
				'</div>',
				'<div class="cl" pub-name="highGrid" pub-mod="admin/customer/grid/customer.base"/>'
			].join('')));


			if(!c.hasHead){
				el.find('.M-formHead').hide();
			}

			var config = {
				'highGrid': util.extend(c.grid_config, {
					'hasBatch': false,
					'eventDataLoad': true,
					'hasSearch': true,
					'gridName': 'user'
				})
			};
			//如果是子表格，则将id作为grid的param
			if(c.isSubGrid && c.param.condition){
				config.highGrid.param = c.param;
			}

			self.buildFromTemplate(config);
			if(!c.isSubGrid){
				var sidebarItems = [];
				// 代理不显示客户类型过滤
				var user = pubjs.getUserCurrent();
				if(user.Type !== 1){
					//类型
					sidebarItems.push(
						{'name': 'type', 'uri':'modules/sideBarBase.radio','config':{
							'title': LANG('类型：'),
							'data': [
								{id: 0, name: LANG('所有')}
								,{id: 1, name: LANG('代理')}
								,{id: 2, name: LANG('直客')}
							],
							'value': 0
						}}
					);
				}
				sidebarItems = sidebarItems.concat(
					[
						//发票信息
						{'name': 'invoice', 'uri':'modules/sideBarBase.radio','config':{
							'title': LANG('发票信息：'),
							'data': [
								{id: 0, name: LANG('所有')}
								,{id: 1, name: LANG('资料不全')}
								,{id: 2, name: LANG('待审核')}
								,{id: 3, name: LANG('已通过')}
								,{id: 4, name: LANG('已拒绝')}
							],
							'value': 0
						}},
						{'name': 'depth', 'uri':'modules/sideBarBase.checkbox', 'config': {
							'title': LANG('结果设置：'),
							'data': [
								{id: 1, name: LANG('只显示一级客户')}
							]
						}},
						{'name': 'isDeleted', 'uri':'modules/sideBarBase.radio','config':{
							'title': LANG('状态：'),
							'data': [
								{id: 0, name: LANG('有效')},
								{id: 1, name: LANG('已归档')},
							],
							'value': 0
						}}
					]
				);
				self.createAsync('slotSidebar', '@layout/v1/sidebar.base', {
					'target': c.targetSidebar,
					'items': sidebarItems
				});
			}

			self.createAsync('manualDenyPopwin', 'admin/customer/popwin/manualDeny.base');
		},
		// 操作列点击事件
		onOperateMenuShow: function(ev) {
			var status = ev.param.Status;
			var CreateUserId = ev.param.CreateUserId;
			var returnList = [];

			// todo 暂时去掉下线财务申请这个功能
			//if(this.$financeAuditAddRight){
			//	returnList.push({
			//		'id':'financeAuditApply',
			//		'name':LANG('财务申请')
			//	});
			//}

			// 有充值操作的权限, 同时当前用户是该客户的直属上级
			if (pubjs.checkRight('user.recharge') && (pubjs.getUserId() == CreateUserId))
			{
				returnList.push({
					'id': 'charge',
					'name': LANG('充值')
				});
			}

			if (this.$userBudgetRight) {
				returnList.push({
					'id': 'userBudget',
					'name': LANG('预算设置')
				});
			}

			returnList =  returnList.concat( [
				{
					'id': 'invoice',
					'name': LANG('发票')
				},
				{
					'id': 'changeLogin',
					'name': LANG('伪登录')
				}
			]);

			if (pubjs.checkRight('user.update'))
			{
				returnList.push(
					{
						'id': 'edit',
						'name': LANG('编辑')
					}
				);
			}


			if (pubjs.checkRight('user.stopUser'))
			{
				//1 正常  2禁止
				switch (status){
					case 2:
						returnList.push({'id': 'enable','name': LANG('启用')});
						break;
					case 1:
						returnList.push({'id': 'stop','name': LANG('禁用')});
						break;
				}
			}


			if (pubjs.checkRight('user.remove'))
			{
				returnList.push({'id': 'remove','name': LANG('删除')});
			}

			ev.returnValue = returnList;
			return false;
		},
		// 操作列选项点击事件
		onOperateMenuSelect: function(ev) {
			var self = this;
			var key = ev.param[0]['key'];
			var selectedUser = ev.param[1];

			var id = +selectedUser['UserId'];
			//新版dsp没有员工，campanyId与_id相同
			var campanyId = +selectedUser['_id'];
			var UserName = selectedUser['UserName'];
			// var id = +ev.param[1]['_id'];
			switch (key){
				case 'charge':
					self.chargePopwin(id);
					break;
				case 'financeAuditApply':
					self.applyFinanceAudit(selectedUser);
					break;
				case 'invoice':
					self.invoicePopwin(campanyId);
					break;
				case 'changeLogin':
					self.changeLogin(id);
					break;
				case 'edit':
					pubjs.controller.navigate('admin/customer/edit/' + id);
					break;
				case 'enable':
				case 'stop':
					self.toggleStatus(id, key);
					break;
				case 'remove':
					self.removeCustomer(id, UserName);
					break;
				case 'userBudget':
					self.setUserBudget(id);
			}

		},
		//响应添加客户按钮
		//可以修改跳转的连接
		onInputClick: function(ev){
			if(ev.name == 'addButton'){
				pubjs.controller.navigate('admin/customer/edit');
			}
			return false;
		},
		//响应右边侧边栏选项
		onSidebarFilter: function(ev){
			var self = this
				,param = {};

			util.each(ev.param, function(item, idx){
				var type = idx;
				var id = item.id;

				switch (type) {
					case 'type':
						param.Type = +id;
						break;
					case 'invoice':
						param.InvoiceStatus = +id;
						break;
					case 'depth':
						if(item.data && item.data.length){
							util.each(item.data, function(sub){
								if(sub){
									switch (sub.id){
										case 1:
											param.Depth = sub.checked ? 1 : null;
											break;
									}
								}
							});
						}
						break;
				}
			});

			self.$.highGrid.reload(param);
		},
		//充值弹窗
		chargePopwin: function(id){
			var self = this;
			if(self.$.chargePopwin) {
				self.$.chargePopwin.reset();
				self.$.chargePopwin.show();
				self.$.chargePopwin.load(id);
			}
			else {
				self.createAsync('chargePopwin','admin/customer/popwin/charge.base', function( mod ) {
					mod.reset();
					mod.show().load(id);
				});
			}
		},
		//发票弹窗
		invoicePopwin: function(id){
			var mod = this.$.invoicEdit;
			if(!mod){
				this.createAsync('invoicEdit','admin/invoiceManage/popwin/edit.base',
					{
						'admin': true
					},
					function(mod){
						mod.load(id).show();
				});
			}
			else{
				mod.reset();
				mod.load(id).show();
			}
		},
		//伪登录操作
		changeLogin: function(id){
			var self = this;
			if(!id){
				return false;
			}
			var urlSwitchUser = self.getConfig().urlSwitchUser;
			pubjs.loading.show();
			pubjs.mc.send(urlSwitchUser, {'id': id}, self.onChangeLogin.bind(self));
		},
		onChangeLogin : function(err) {
			pubjs.loading.hide();
			if( err ) {
				pubjs.alert(err.message);
			}
			else {
				window.location.reload();
			}
		},
		//禁止和启动操作
		toggleStatus: function(id, key){

			var manualDeny = this.get('manualDenyPopwin');

			var map = {
				'enable': 1,   //启用
				'stop': 2      //手动禁止
			}
			var status = map[key];
			var statusText = (status == 1 ? LANG('启用') : LANG('禁用'));
			var userData = this.$.highGrid.getData(+id);
			if(!userData){
				return false;
			}
			var type = userData.Type;

			var param = {
					'_id': id,
					'Status': status,
					'Direct': 0
				};

			// 客户类型为代理时，询问是否要改变其下属帐号
			if(+type == 1 && status == 2){
				pubjs.confirm(LANG('正在%1帐号：%2，是否要同时改变其下属代理和直客的帐号状态？', statusText, userData.UserName),
					function(isOk){
						//Direct: 1 禁用所属代理以及直客的帐号，如果只禁用当前账号，此参数为0
						param['Direct'] = isOk ? 1 : 0;
					}
				);
			}

			if(manualDeny){
				manualDeny.reset();
				manualDeny.show();
				manualDeny.setParam(param);
			}

		},
		onToggleStatus: function(){
			pubjs.alert('修改成功');
			this.reload();
			return false;
		},
		//删除操作
		removeCustomer: function(id, name){
			if( !id ) {
				return false;
			}
			var self = this;
			pubjs.confirm(LANG('真的要删除（%1）的客户账户吗?', name),function(isOk){
				if(isOk){
					pubjs.mc.send(self.getConfig('urlRemove'),{'_id': id},
						self.onRemove.bind(self)
					);
				}
			});
		},
		onRemove: function( err, data ) {
			if(err) {
				pubjs.alert(err.message);
				return false;
			}
			pubjs.alert('删除成功');
			this.reload();
		},
		reload: function( param ) {
			this.$.highGrid.setParam( param ).reload();
		},
		//编辑发票的弹窗
		applyFinanceAudit: function(user){

			var mod = this.$.financeAuditApply;
			if(!mod){
				this.createAsync('financeAuditEdit','admin/financeAudit/popwin/edit.base',function(mod){
					mod.loadUser(user.UserId).show();
					this.$.financeAuditApply = mod;
				});
			} else{
				mod.reset().loadUser(user.UserId).show();
			}
		},
		onProcessSuccess: function(){
			this.reload();
		},
		onChargeSuccess: function(){
			this.reload();
		},
		// 设置每日预算
		setUserBudget: function(id){
			var popwin = this.$.budgetPopwin;
			if (popwin) {
				popwin.reset()
					.show()
					.load(id);
			}
			else {
				this.createAsync(
					'budgetPopwin','admin/customer/popwin/budget.base',
					function(mod) {
						mod.reset()
							.show()
							.load(id);
					}
				);
			}
		},
		onGridDataLoad: function() {
			//如果没有设置溢价的权限，则隐藏溢价信息。
			if(this.$.highGrid && !pubjs.checkRight('user.setPremium')){
				this.$.highGrid.toggleColumn('CostRateTmp', false);
			}
		}
	});
	exports.main = Main;
});